package com.hdd.utils.wxEncrypt;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

public class WXCore {
    
    private static final String WATERMARK = "watermark";
    private static final String APPID = "appid";
    /**
     * 解密数据
     * @return
     * @throws Exception
     */
    public static String decrypt(String appId, String encryptedData, String sessionKey, String iv){
        String result = "";
        try {
            AES aes = new AES();  
            byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));  
            if(null != resultByte && resultByte.length > 0){  
                result = new String(WxPKCS7Encoder.decode(resultByte));  
                JSONObject jsonObject = JSONObject.parseObject(result);
                String decryptAppid = jsonObject.getJSONObject(WATERMARK).getString(APPID);
                if(!appId.equals(decryptAppid)){
                    result = "";
                }
            }  
        } catch (Exception e) {
            result = "";
            e.printStackTrace();
        }
        return result;
    }
    
    
    public static void main(String[] args) throws Exception{
       String appId = "wx59c864c7d2fc6536";
       String encryptedData = "97dnxt2kDxttURZnJZ0uUlThKH0aOZkTnMTpz4gwN4r6FASEjqlIr074lTgD+AQuPqCLTyAafzElYSN/LAoyfcRzkW0Tvol3X040xYk+ZFfxnHjF3xnhdvjpviVUoQ71961MJRSMCnMbBXkba64brg4IQeW0VYx4wmQaOz4FWtDRdL7XdEULdZiT2G8R0oJHiAwQIxsQ+voLMWdSUHjUyQ==";
       String sessionKey = "u+NyRuyTFRYHhEWmEE0eVA==";
       String iv = "ma9Nq292Y4UIcB3nyUqt0g==";
       System.out.println(decrypt(appId, encryptedData, sessionKey, iv));
    }


}
